package cn.xiaobai.j2exe.controller;

import cn.hutool.core.io.FileUtil;
import cn.xiaobai.j2exe.AbstractApplication;
import cn.xiaobai.j2exe.StageManager;
import cn.xiaobai.j2exe.consts.ValuesConstant;
import cn.xiaobai.j2exe.utils.DialogUtils;
import cn.xiaobai.j2exe.utils.FileUtils;
import cn.xiaobai.j2exe.utils.SourceUtils;
import cn.xiaobai.j2exe.utils.TaskPool;
import com.badlogicgames.packr.Packr;
import com.badlogicgames.packr.PackrConfig;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.control.Tooltip;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

/**
 * 主窗体控制, 并处理菜单和导航栏的功能
 *
 * @Author yangdaji
 * @Date 2023/12/26
 * @PackageName cn.xiaobai.j2exe.controller
 * @ClassName MainController
 */
public class MainController extends AbstractApplication {

    @FXML
    private Button open_bt;

    @FXML
    private Button save_bt;

    @FXML
    private Button run_bt;

    //  功能按钮

    @FXML
    private Button usage_bt;

    @FXML
    private Button exe_bt;

    @FXML
    private Button app_bt;

    @FXML
    private Button jvm_selection_bt;

    /**
     * 功能容器, root 容器
     */
    @FXML
    private AnchorPane feat_pane;


    // title start

    /**
     * 打开文件
     */
    @FXML
    public void on_open_bt_Click() {
        // 设置缓存目录
        fileChooser.setTitle("请选择打开的配置文件");
        File file = fileChooser.showOpenDialog(feat_pane.getScene().getWindow());
        // 打开一个配置, 如果未选择任何配置则不处理
        if (cacheAndRead(file, false)) {
            // 读取数据更新到转换数据中
            updateData();
            // 刷新全部页面数据
            refreshData();
        }
    }

    /**
     * 保存配置
     */
    @FXML
    public void on_save_bt_Click() {

        // 设置缓存目录, 需要一个缓存文件
        fileChooser.setTitle("请选择配置文件保存位置");
        File file = fileChooser.showSaveDialog(feat_pane.getScene().getWindow());
        // 保存一个配置, 如果取消或者其他则不处理
        if (cacheAndRead(file, false)) {
            // 配置写入文件
            TaskPool.submit(() -> FileUtils.writeFormatToJson(globalConvertConfig, file, false));
        }
    }


    private final Packr packr = new Packr();

    /**
     * 执行转换
     */
    @FXML
    public void on_run_bt_Click() {

        boolean isException = false;
        try {
            globalConvertConfig.verifyConf();
        } catch (IOException e) {
            isException = true;
            DialogUtils.popUp("异常", e.getMessage());
        }
        // 验证没问题后可以转换
        if (!isException) {
            TaskPool.submitFx(this::jarToExe);
        }
    }

    private void jarToExe() {
        PackrConfig packrConfig = globalConvertConfig.toPackageConf();
        try {
            packr.pack(packrConfig);
        } catch (Exception e) {
            DialogUtils.popUp("异常", e.getMessage());
        }
    }

    // title end

    /**
     * 功能按钮点击显示, 包含 exe, app, jvm 选项, jvm 配置功能按钮
     *
     * @param mouseEvent 鼠标事件
     */
    @FXML
    public void on_bt_to_view_click(MouseEvent mouseEvent) {
        // 获取鼠标点击源
        Object source = mouseEvent.getSource();
        if (source instanceof Button bt) {
            show(bt);
        }
    }

    @Override
    protected void updateInitDir() {
        // 配置目录
        File initialDirCache = cacheConfig.getInitialDirCache();
        if (FileUtil.isNotEmpty(initialDirCache) &&
                !initialDirCache.equals(fileChooser.getInitialDirectory())) {
            fileChooser.setInitialDirectory(initialDirCache);
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        addListener(this);

        initResource();
        initData();
    }

    /**
     * 初始化缓存数据
     */
    private void initData() {
        cacheAndRead(null, true);
        //添加扩展选项过滤器
        fileChooser.getExtensionFilters()
                .addAll(new FileChooser.ExtensionFilter("all files", "*.*"),
                        new FileChooser.ExtensionFilter("text files", "*.txt"),
                        new FileChooser.ExtensionFilter("json files", "*.json"),
                        new FileChooser.ExtensionFilter("zip files", "*.jar")
                );
    }

    /**
     * 初始化静态资源, 图标设置
     */
    private void initResource() {
        // 标题
        open_bt.setGraphic(new ImageView(SourceUtils.getPngImg("open-20.png")));
        open_bt.setTooltip(new Tooltip("open config"));

        save_bt.setGraphic(new ImageView(SourceUtils.getPngImg("save-20.png")));
        save_bt.setTooltip(new Tooltip("save config"));

        run_bt.setGraphic(new ImageView(SourceUtils.getPngImg("run-20.png")));
        run_bt.setTooltip(new Tooltip("run jar to exe"));

        // 功能
        usage_bt.setGraphic(new ImageView(SourceUtils.getPngImg("usage-32.png")));
        usage_bt.setTooltip(new Tooltip("USAGE COURSE"));

        exe_bt.setGraphic(new ImageView(SourceUtils.getPngImg("exe-40.png")));
        exe_bt.setTooltip(new Tooltip("EXE")); // 设置悬停提示

        app_bt.setGraphic(new ImageView(SourceUtils.getPngImg("app-32.png")));
        app_bt.setTooltip(new Tooltip("APP"));

        jvm_selection_bt.setGraphic(new ImageView(SourceUtils.getPngImg("jvm-selection-32.png")));
        jvm_selection_bt.setTooltip(new Tooltip("JVM SELECTION"));

        // 初始化关闭运行按钮
        run_bt.setDisable(true);
        setRun_bt(run_bt);
        // 绑定root 容器
        bindRootPane(feat_pane);

        initFxmlView();
    }

    /**
     * 初始化子界面视图
     */
    private void initFxmlView() {
        URL usageUrl = SourceUtils.getFxml(ValuesConstant.USAGE_VIEW_FXML);
        URL exeUrl = SourceUtils.getFxml(ValuesConstant.EXE_CONF_FXML);
        URL appUrl = SourceUtils.getFxml(ValuesConstant.APP_CONF_FXML);
        URL JvmSelectUrl = SourceUtils.getFxml(ValuesConstant.JVM_SELECTION_FXML);


        FXMLLoader usageNode = new FXMLLoader(usageUrl);
        FXMLLoader exeNode = new FXMLLoader(exeUrl);
        FXMLLoader appNode = new FXMLLoader(appUrl);
        FXMLLoader jvmSelectNode = new FXMLLoader(JvmSelectUrl);

        StageManager.putFxml(usage_bt.getId(), usageNode);
        StageManager.putFxml(exe_bt.getId(), exeNode);
        StageManager.putFxml(app_bt.getId(), appNode);
        StageManager.putFxml(jvm_selection_bt.getId(), jvmSelectNode);

        // 首页展示
        show(usage_bt);
    }
}